package com.promise.jokerdream.response.pc

import com.promise.jokerdream.model.knight.FightRecord
import com.promise.jokerdream.model.knight.FightResult
import com.promise.jokerdream.model.knight.KnightFightInfo
import com.promise.jokerdream.model.knight.PlayerFormation
import kotlinx.serialization.Serializable

@Serializable
data class QueryKnightFightResponse(
    override val result: Int,
    override val msg: String = "",
    val string: String = "",
): BasePCResponse {
    override fun getDescription(): String {
        return msg
    }

    /**
     * 解析所有战斗记录
     * @return 战斗记录列表，每个元素代表一次战斗
     */
    fun parseFightRecords(): List<FightRecord> {
        if (string.isEmpty()) {
            return emptyList()
        }

        val fightRecords = mutableListOf<FightRecord>()
        
        // 按 || 分割多个战斗记录
        val records = string.split("||").filter { it.isNotEmpty() }
        
        for (record in records) {
            // 解析Player1和Player2
            val player1Formation = parsePlayerData(record, 1) ?: continue
            val player2Formation = parsePlayerData(record, 2) ?: continue
            
            // 解析Win信息
            val winPattern = Regex("&Win:(\\d+)")
            val winMatch = winPattern.find(record)
            val winner = winMatch?.groupValues?.get(1)?.toIntOrNull() ?: -1
            val fightResult = FightResult(winner = winner)
            
            fightRecords.add(
                FightRecord(
                    player1Formation = player1Formation,
                    player2Formation = player2Formation,
                    result = fightResult
                )
            )
        }
        
        return fightRecords
    }
    
    /**
     * 解析所有战斗记录中的两个玩家阵容信息（去重后的）
     * @return Triple<Player1阵容, Player2阵容, 战斗记录列表>，如果解析失败返回null
     */
    fun parseFirstFightFormations(): Triple<PlayerFormation, PlayerFormation, List<FightRecord>>? {
        if (string.isEmpty()) {
            return null
        }
        
        // 解析所有战斗记录
        val fightRecords = parseFightRecords()
        
        if (fightRecords.isEmpty()) {
            return null
        }
        
        // 从所有战斗记录中提取Player1和Player2的所有侠士，去重
        val player1Knights = mutableMapOf<String, KnightFightInfo>() // 使用name作为key去重
        val player2Knights = mutableMapOf<String, KnightFightInfo>()
        
        for (record in fightRecords) {
            // 收集Player1的所有侠士
            for (knight in record.player1Formation.knights) {
                if (!player1Knights.containsKey(knight.name)) {
                    player1Knights[knight.name] = knight
                }
            }
            
            // 收集Player2的所有侠士
            for (knight in record.player2Formation.knights) {
                if (!player2Knights.containsKey(knight.name)) {
                    player2Knights[knight.name] = knight
                }
            }
        }
        
        val player1Formation = PlayerFormation(
            playerNumber = 1,
            knights = player1Knights.values.toList()
        )
        
        val player2Formation = PlayerFormation(
            playerNumber = 2,
            knights = player2Knights.values.toList()
        )
        
        return Triple(player1Formation, player2Formation, fightRecords)
    }

    /**
     * 解析单个玩家的数据
     * @param record 战斗记录字符串
     * @param playerNumber 玩家编号（1或2）
     * @return 玩家阵容信息，如果解析失败返回null
     */
    private fun parsePlayerData(record: String, playerNumber: Int): PlayerFormation? {
        val playerPattern = Regex("&Player$playerNumber:([^&]+)")
        val matches = playerPattern.findAll(record)
        
        val knights = mutableListOf<KnightFightInfo>()
        
        // 匹配角色名(角色ID)格式的正则
        val nameIdPattern = Regex("([^(]+)\\(([^)]+)\\)")
        
        // 遍历所有匹配的Player数据块
        for (match in matches) {
            val playerData = match.groupValues[1]
            val parts = playerData.split(";").filter { it.isNotEmpty() }
            
            if (parts.size < 2) {
                continue
            }
            
            // 跳过第一个部分（标志位，通常是0）
            val index = 1
            
            // 解析当前数据块中的侠士
            val currentPart = parts[index]
            
            // 尝试匹配角色名(角色ID)格式
            val nameIdMatch = nameIdPattern.find(currentPart) ?: continue
            
            val name = nameIdMatch.groupValues[1]
            val id = nameIdMatch.groupValues[2]
            
            // 检查是否有足够的后续数据（至少需要6个字段：等级、血量、力量、速度、敏捷、技能）
            if (index + 5 >= parts.size) {
                continue
            }
            
            val level = parts[index + 1].toIntOrNull() ?: continue
            val hp = parts[index + 2].toIntOrNull() ?: continue
            val strength = parts[index + 3].toIntOrNull() ?: continue
            val agility = parts[index + 4].toIntOrNull() ?: continue
            val speed = parts[index + 5].toIntOrNull() ?: continue
            
            // 解析技能 - 从第7个字段开始（index + 6），灵活解析所有技能
            val skills = mutableListOf<Int>()
            var skillIndex = index + 6
            
            // 尝试解析最多5个技能字段
            while (skillIndex < parts.size && skills.size < 5) {
                val skillField = parts[skillIndex]
                
                if (skillField.isEmpty()) {
                    skillIndex++
                    continue
                }
                
                // 如果字段包含逗号，说明是多个技能用逗号分隔
                if (skillField.contains(",")) {
                    skillField.split(",").forEach { skillStr ->
                        skillStr.trim().toIntOrNull()?.let { skillId ->
                            if (skillId > 0) { // 过滤掉0或无效的技能ID
                                skills.add(skillId)
                            }
                        }
                    }
                } else {
                    // 单个技能
                    skillField.toIntOrNull()?.let { skillId ->
                        if (skillId > 0) { // 过滤掉0或无效的技能ID
                            skills.add(skillId)
                        }
                    }
                }
                
                skillIndex++
            }
            
            knights.add(
                KnightFightInfo(
                    name = name,
                    id = id,
                    level = level,
                    hp = hp,
                    strength = strength,
                    speed = speed,
                    agility = agility,
                    skills = skills
                )
            )
        }
        
        return if (knights.isNotEmpty()) {
            PlayerFormation(
                playerNumber = playerNumber,
                knights = knights
            )
        } else {
            null
        }
    }
}
